import React from 'react';
import {connect} from 'react-redux';
import CCEFService from 'containers/enterprise-manage/company-maintain/company-extend-filed.service';
import 'styles/enterprise-manage/org-structure/department-extend-filed/department-extend-filed.scss'
import ExtendFieldComponent from 'components/template/extend-field-setting/extend-field';
import {messages} from "share/common";
import BaseService from 'share/base.service';
import {message} from 'antd';
import supplierService from 'containers/supplier-maintenance/supplier-management.service';
//待添加的字段类型
let customFromOriginList = [];
class SupplierExtendFiledBank extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      authPolicyAll: false, // 是否为全租户
      orgPermission: {}, // 当前页面的组织权限
      loading: false,
      data: [],
      customFromOriginList: [],//可以选择表单类型
      customFrom: {},//配置的表单
    }
  }

  activeIndex = 0;

  componentDidMount() {
    this.getWidgetList();
  }
  // 获取表单字段类型
  getWidgetList = () => {
    CCEFService.getWidgetList({type: 1003})
      .then((res) => {
        let list = [];
        //只要两种类型
        res.data.map((item)=>{
          if(item.messageKey === "cust_list" || item.messageKey === "input"){
            list.push(item)
          }
        });
        customFromOriginList = list;
        this.getCustomForm();
      })
  };

  setCustomFormFieldI18nDTOS = (originCustomFormFields)=> {
    let nowWidget = originCustomFormFields;
    //counterFlag为内部组件排序所需key值，在此处初始化
    nowWidget.map((widget, index) => {
      //添加一个 fieldCodeForDisabled 主要用来实现有编码不能编辑的功能
      widget.fieldCodeForDisabled = widget.fieldCode;
      //联动开关要用
      if(!widget.customFormFieldI18nDTOS || widget.customFormFieldI18nDTOS.length === 0){
        widget.customFormFieldI18nDTOS = [];
        this.props.languageList.map(language => {
          let i18nDTO = {
            fieldName: widget.fieldName,
            promptInfo: widget.promptInfo,
            language: language.code
          };
          widget.customFormFieldI18nDTOS.push(i18nDTO);
        });
      }

      if (!widget.i18n) {
        widget.i18n = {};
      }
      if (!widget.i18n.fieldName || !widget.i18n.fieldName.length) {
        let fieldNameI18n = [];
        this.props.languageList.map(language => {
          let i18nDTO = {
            language: language.code,
            value: widget.fieldName ? widget.fieldName : ''
          };
          fieldNameI18n.push(i18nDTO);
        });
        widget.i18n.fieldName = fieldNameI18n;
      }

      if (!widget.i18n.promptInfo || !widget.i18n.promptInfo.length) {
        let promptInfoI18n = [];
        this.props.languageList.map(language => {
          let i18nDTO = {
            language: language.code,
            value: widget.promptInfo ? widget.promptInfo : ''
          };
          promptInfoI18n.push(i18nDTO);
        });
        widget.i18n.promptInfo = promptInfoI18n;
      }
      return widget;
    });
  }
  // 获取表单
  getCustomForm = () => {
    // 如果没有需要前端初始化创建
    supplierService.getCustomForm('vendor_bank_account_attach_form')
      .then((res) => {
        if(!res || !res.data){
          //没有获取到表单  则新建表单
          let customFrom = {
            customFormFields: [],
            formCode: 'vendor_bank_account_attach_form',
            messageKey: "vendor_bank_account_attach_form"
          };
          this.setState({
            customFrom,
            customFromOriginList
          });
          return;
        }
        let customFrom = res.data;
        if (customFrom.customFormFields && customFrom.customFormFields.length > 0) {
          this.setCustomFormFieldI18nDTOS(customFrom.customFormFields);
        }
        if (customFrom.customFormFields && customFrom.customFormFields.length > 0) {
          customFrom.customFormFields[this.activeIndex]._active = true;
        }
        this.setState({
          loading: false,
          customFrom,
          customFromOriginList
        })
      })
  };
  // 创建更新入口
  createOrUpdate = (form) => {
    form.customFormFields.map((item, index)=>{
      delete item.systemSequence;
      if(item._active) {
        this.activeIndex = index;
      }
    });
    if(!form.formOID) {
      this.createCustomForm(form)
    } else {
      this.updateCustomForm(form)
    }
  };
  // 创建表单：这个表单在租户创建的时候初始化
  createCustomForm = (form) => {
    this.setState({
      loading: true,
    });
    supplierService.createCompanyCustomForm(form)
      .then((res) => {
        message.success(messages('basic-5.key149')/*创建成功*/);
        this.setState({
          loading: false,
        });
        this.getCustomForm();
        // 这个地方需要更新一下functionProfile，因为创建表单之后，接口数据变化了
        BaseService.getProfile();
      }).catch(()=>{this.setState({ loading: false})})
  };
  // 更新表单
  updateCustomForm = (form) => {
    if(!form.formOID){
      //只有当新增之后，立即再次更新执行这个逻辑
      form.formOID = this.props.profile["company.custom.form"]
    }
    this.setState({
      loading: true,
    });
    CCEFService.updateCustomForm(form)
      .then((res) => {
        message.success(messages('basic-5.key72')/*更新成功*/);
        this.getCustomForm();
        this.setState({
          loading: false,
        })
      }).catch(()=>{this.setState({ loading: false})})
  };
  // 取消
  cancel = () => {
    window.history.back(-1);
  };

  // 获取扩展字段表单
  render() {
    const {loading, customFrom, customFromOriginList} = this.state;
    const {authPolicyAll} = this.props;
    return (
      <div className="extend-field-wrap">
        <ExtendFieldComponent
          loading={loading}
          filedMax={20}
          cancel={this.cancel}
          rightIsShow={authPolicyAll}
          bottomBtnIsShow={authPolicyAll}
          leftDragable={authPolicyAll}
          saveFrom={this.createOrUpdate}
          customFrom={customFrom}
          customFromOriginList={customFromOriginList}
        />
      </div>
    )
  }
}

SupplierExtendFiledBank.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    profile: state.login.profile,
    user: state.login.user,
    authPolicyAll: state.main.authPolicyAll,
    company: state.login.company,
    language: state.main.language,
    languageList: state.login.languageList,
  }
}

export default connect(mapStateToProps)(SupplierExtendFiledBank);



